//
//  LoginView.m
//  eticket
//
//  Created by AnhQuocNguyen on 4/17/13.
//  Copyright (c) 2013 SoinMedia. All rights reserved.
//

#import "LoginView.h"

@implementation LoginView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)dealloc {
    [_txtEmail release];
    [_txtPass release];
    [_btnSubmit release];
    [super dealloc];
}


#pragma mark - setupLoginView
- (void)setupLoginView{
    _txtEmail.delegate = self;
    _txtPass.delegate = self;
    _txtPass.secureTextEntry = YES;
}


#pragma mark - Textfield Delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    remClickText = textField;
    NSLog(@"textFieldShouldBeginEditing");
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}


#pragma mark - TouchEvent
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [remClickText resignFirstResponder];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
     [remClickText resignFirstResponder];
}


#pragma mark - Become & Resign textfield
- (void)textFieldResignFirstResponder{
    if (remClickText && [remClickText isFirstResponder]) {
        [remClickText resignFirstResponder];
    }
}
- (void)textFieldbecomeFirstResponder{
    if ([remClickText canBecomeFirstResponder]) {
        [remClickText becomeFirstResponder];
    }
}

- (void)alertTextField:(NSString *)message{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    alert.tag = ALERT_MESSAGE;
    [alert show];
    SAFE_RELEASE_OBJECT(alert);
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.tag == ALERT_MESSAGE) {
        [self textFieldbecomeFirstResponder];
    }
}

#pragma mark - MBProgressHUD
-(void)initHUD:(NSString *)alert {
    if (mHud) {
        [mHud removeFromSuperview];
        SAFE_RELEASE_OBJECT(mHud);
    }
    mHud = [[MBProgressHUD alloc] initWithView:self];
    //    mHud.delegate = self;
    mHud.labelText = alert;
    mHud.dimBackground = YES;
    [self addSubview:mHud];
    
}
-(void)waitting{
    while (mLoading) {
        usleep(5000);
        if (_countTimeout >= 187*20 /* 187 ~ 3s ==>> 187 *20 ~ 1' */) {
            mLoading = NO;
            
        }
    }
}
////////////////////////////////////////////////////////////////////////////////
- (BOOL)checkValidateTextField{
    NSString *strEmail = [Utilities trimString:_txtEmail.text];
    if ([Utilities isEmptyString:strEmail] || ![Utilities isValidEmail:strEmail]) {
        remClickText = _txtEmail;
        [self alertTextField:@"Email is invalid !!!"];
        return  NO;
    }
    
    //Check Password
    NSString *password = [Utilities trimString:_txtPass.text];
    if ([Utilities isEmptyString:password] || [password length] < 6) {
        remClickText = _txtPass;
        [self alertTextField:@"Password is not empty & must be greater than 6 characters !!!"];
        return NO;
    }
    
    if ([Utilities haveEmoji:password]) {
        remClickText = _txtPass;
        [self alertTextField:@"Password must be not emoji !!"];
        return NO;
    }
    
    return YES;
}

- (void)submitToLogin{
//    /users/signin/ -> Post data để login . Parameters cần thiết (email,password,os_version,os_name,device_name);
    
    mLoading = YES;
    [self initHUD:@"Submitting...."];
    [mHud showWhileExecuting:@selector(waitting) onTarget:self withObject:nil animated:NO];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@%@", URL_island_API, signin_API, TOKEN__island];
    NSURL *url = [NSURL URLWithString:urlString];
    
    __block ASIFormDataRequest *requestServer = [ASIFormDataRequest requestWithURL:url];
    [requestServer setTimeOutSeconds:20];
    [requestServer addPostValue:[Utilities trimString:_txtEmail.text] forKey:@"email"];
    [requestServer addPostValue:[Utilities trimString:_txtPass.text] forKey:@"password"];
    [requestServer addPostValue:[[UIDevice currentDevice] systemVersion]forKey:@"os_version"];
    [requestServer addPostValue:@"IOS" forKey:@"os_name"];
    [requestServer addPostValue:[[UIDevice currentDevice] name] forKey:@"device_name"];
    
    ///////////////////////////////////////////////////////
    [requestServer setCompletionBlock:^{
        mLoading = NO;
        NSError *error = nil;
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:[requestServer responseData] options:kNilOptions error:&error];
        NSLog(@"%@", jsonData);
        
        //Check error server
        if (error) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[error description] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
            return;
        }
        
        
        //Check error json
        NSDictionary *jsonError = [jsonData objectForKey:@"error"];
        if ([[jsonError objectForKey:@"code"] intValue] != 200) {
            NSArray *messageArray = [jsonError objectForKey:@"message"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[messageArray objectAtIndex:0] delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
            [alert show];
            SAFE_RELEASE_OBJECT(alert);
            return;
        }
        
        NSDictionary *dataDic = [jsonData objectForKey:@"data"];
        NSString *strAccess_token = [dataDic objectForKey:@"access_token"];
        
        NSDictionary *userDic = [dataDic objectForKey:@"user"];
        NSString *fullname = [userDic objectForKey:@"firstname"];
        
        ////////////////////////////////////////////////////////////
        //Set Login userDefault
        NSUserDefaults *loginUserDefault = [NSUserDefaults standardUserDefaults];
        [loginUserDefault setObject:@"YES" forKey:LOGINED];
        [loginUserDefault synchronize];
        
        
        NSUserDefaults *fullNameUserDefaule = [NSUserDefaults standardUserDefaults];
        [fullNameUserDefaule setObject:fullname forKey:Login_name];
        [fullNameUserDefaule synchronize];
        
        
        NSUserDefaults *accToken = [NSUserDefaults standardUserDefaults];
        [accToken setObject:strAccess_token forKey:access_token_eTicket_userDefault];
        [accToken synchronize];
        ////////////////////////////////////////////////////////////
        
        
        
        _txtEmail.text = @"";
        _txtPass.text = @"";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Login successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        SAFE_RELEASE_OBJECT(alert);
        
        if ([_loginViewDelegate respondsToSelector:@selector(loginView:didLoginSuccessfull:)]) {
            [_loginViewDelegate loginView:self didLoginSuccessfull:fullname];
        }
    }];
    
    
    ///////////////////////////////////////////////////////
    [requestServer setFailedBlock:^{
        mLoading = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Submit faild !!!" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];
        [alert show];
        SAFE_RELEASE_OBJECT(alert);
    }];
    [requestServer startSynchronous];
}


- (IBAction)btnSubmit_Clicked:(id)sender{
    if (![self checkValidateTextField]) {
        return;
    }
    [self textFieldResignFirstResponder];

    [self submitToLogin];
}


#pragma mark - btnForgetPassword_Clicked
- (IBAction)btnForgetPassword_Clicked:(id)sender{
    
    
    if (!_forgetView) {
        POOL_START
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ForgetView" owner:self options:nil];
        _forgetView = (ForgetView *)[nib objectAtIndex:0];
        _forgetView.frame = CGRectMake(330, [Utilities isDeviceFourInches] ? 38 : 43, 320, [UIScreen mainScreen].bounds.size.height - 43);
        _forgetView.forgetViewDelegate = self;
        [_forgetView setupForgetPassword];
        [self.superview addSubview:_forgetView];
        POOL_END
    }
    
    
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = - 320;
        self.frame = frameTempCategory;
        
        CGRect frametemp = _forgetView.frame;
        frametemp.origin.x = 0;
        _forgetView.frame = frametemp;
        
        
    } completion:^(BOOL finished) {
        self.hidden = YES;
        if ([_loginViewDelegate respondsToSelector:@selector(loginView:tapForgetPassword:)]) {
            [_loginViewDelegate loginView:self tapForgetPassword:nil];
        }
    }];
}

- (void)forgetViewWithBack:(ForgetView *)forgetView{
    self.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        
        CGRect frameTempCategory = self.frame;
        frameTempCategory.origin.x = 0;
        self.frame = frameTempCategory;
        
        CGRect frametemp = _forgetView.frame;
        frametemp.origin.x = 330;
        _forgetView.frame = frametemp;
        
    } completion:^(BOOL finished) {
        if ([_loginViewDelegate respondsToSelector:@selector(loginView:forgetViewBack:)]) {
            [_loginViewDelegate loginView:self forgetViewBack:nil];
        }
    }];
}


@end
